package com.cwz.gulimall.seckill.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.cwz.gulimall.common.constant.SeckillConstant;
import com.cwz.gulimall.common.to.mq.SeckillOrderTo;
import com.cwz.gulimall.common.utils.R;
import com.cwz.gulimall.common.vo.MemberRespVo;
import com.cwz.gulimall.seckill.feign.CouponFeignService;
import com.cwz.gulimall.seckill.feign.ProductFeignService;
import com.cwz.gulimall.seckill.interceptor.LoginUserInterceptor;
import com.cwz.gulimall.seckill.service.SeckillService;
import com.cwz.gulimall.seckill.to.SeckillSkuRedisTo;
import com.cwz.gulimall.seckill.vo.SeckillSessionsWithSkus;
import com.cwz.gulimall.seckill.vo.SeckillSkuVo;
import com.cwz.gulimall.seckill.vo.SkuInfoVo;
import org.redisson.api.RSemaphore;
import org.redisson.api.RedissonClient;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service
public class SeckillServiceImpl implements SeckillService {

    @Autowired
    CouponFeignService couponFeignService;

    @Autowired
    ProductFeignService productFeignService;

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Autowired
    RedissonClient redissonClient;

    @Autowired
    RabbitTemplate rabbitTemplate;

    @Override
    public void uploadSeckillSkuLatest3Days() {
        R r = couponFeignService.getLatest3DaySession();
        if (r.getCode() == 0) {
            List<SeckillSessionsWithSkus> data = r.getData(new TypeReference<List<SeckillSessionsWithSkus>>() {
            });
            //redis保存活动信息
            saveSessionInfos(data);
            //redis保存商品信息
            saveSessionSkuInfos(data);
        }
    }

    @Override
    public List<SeckillSkuRedisTo> getCurrentSeckillSkus() {
        long time = new Date().getTime();
        List<SeckillSkuRedisTo> tos = new ArrayList<>();
        Set<String> keys = stringRedisTemplate.keys(SeckillConstant.SESSIONS_CACHE_PREFIX + "*");
        for (String key : keys) {
            String replace = key.replace(SeckillConstant.SESSIONS_CACHE_PREFIX, "");
            String[] s = replace.split("_");
            if (time >= Long.parseLong(s[0]) && time <= Long.parseLong(s[1])) {
                List<String> range = stringRedisTemplate.opsForList().range(key, 0, -1);
                BoundHashOperations<String, String, String> ops = stringRedisTemplate.boundHashOps(SeckillConstant.SKUKILL_CACHE_PREFIX);
                List<String> list = ops.multiGet(range);
                if (list != null) {
                    List<SeckillSkuRedisTo> collect = list.stream().map(item -> {
                        SeckillSkuRedisTo to = JSON.parseObject(item, SeckillSkuRedisTo.class);
                        return to;
                    }).collect(Collectors.toList());
                    return collect;
                }
                break;
            }
        }
        return null;
    }

    @Override
    public SeckillSkuRedisTo getSkuSeckillInfo(Long skuId) {
        BoundHashOperations<String, String, String> ops = stringRedisTemplate.boundHashOps(SeckillConstant.SKUKILL_CACHE_PREFIX);
        Set<String> keys = ops.keys();
        if (keys != null && keys.size() > 0) {
            for (String key : keys) {
                if (key.endsWith(skuId.toString())) {
                    String s = ops.get(key);
                    SeckillSkuRedisTo seckillSkuRedisTo = JSON.parseObject(s, SeckillSkuRedisTo.class);
                    long time = new Date().getTime();
                    Long startTime = seckillSkuRedisTo.getStartTime();
                    Long endTime = seckillSkuRedisTo.getEndTime();
                    if (time <= startTime || time >= endTime) {
                        seckillSkuRedisTo.setRandomCode(null);
                    }
                    return seckillSkuRedisTo;
                }
            }
        }
        return null;
    }

    @Override
    public String seckill(String killId, String key, Integer num) {
        MemberRespVo memberRespVo = LoginUserInterceptor.loginUser.get();
        BoundHashOperations<String, String, String> ops = stringRedisTemplate.boundHashOps(SeckillConstant.SKUKILL_CACHE_PREFIX);
        String value = ops.get(killId);
        if (StringUtils.isEmpty(value)) {
            return null;
        } else {
            SeckillSkuRedisTo seckillSkuRedisTo = JSON.parseObject(value, SeckillSkuRedisTo.class);
            long time = new Date().getTime();
            if (time >= seckillSkuRedisTo.getStartTime() && time <= seckillSkuRedisTo.getEndTime()) {
                String randomCode = seckillSkuRedisTo.getRandomCode();
                String id = seckillSkuRedisTo.getPromotionSessionId() + "_" + seckillSkuRedisTo.getSkuId();
                if (randomCode.equals(key) && killId.equals(id)) {
                    if (num <= seckillSkuRedisTo.getSeckillLimit().intValue()) {
                        String redisKey = memberRespVo.getId() + "_" + id;
                        Boolean aBoolean = stringRedisTemplate.opsForValue().setIfAbsent(redisKey, num.toString(), seckillSkuRedisTo.getEndTime() - time, TimeUnit.MILLISECONDS);
                        if (aBoolean) {
                            RSemaphore semaphore = redissonClient.getSemaphore(SeckillConstant.SKU_STOCK_SEMAPHORE + randomCode);
                            boolean b = semaphore.tryAcquire(num);
                            if (b) {
                                String orderSn = UUID.randomUUID().toString().replace("-", "");
                                SeckillOrderTo seckillOrderTo = new SeckillOrderTo();
                                seckillOrderTo.setOrderSn(orderSn);
                                seckillOrderTo.setSeckillPrice(seckillSkuRedisTo.getSeckillPrice());
                                seckillOrderTo.setMemberId(memberRespVo.getId());
                                seckillOrderTo.setNum(num);
                                seckillOrderTo.setSkuId(seckillSkuRedisTo.getSkuId());
                                seckillOrderTo.setPromotionSessionId(seckillSkuRedisTo.getPromotionSessionId());
                                rabbitTemplate.convertAndSend("order-event-exchange", "order-seckill-order", seckillOrderTo);
                                return orderSn;
                            }

                        }
                    }
                }
            }
        }
        return null;
    }

    private void saveSessionInfos(List<SeckillSessionsWithSkus> data) {
        data.forEach(session -> {
            long startTime = session.getStartTime().getTime();
            long endTime = session.getEndTime().getTime();
            String key = startTime + "_" + endTime;
            if (!stringRedisTemplate.hasKey(SeckillConstant.SESSIONS_CACHE_PREFIX + key)) {
                List<String> ids = session.getRelationSkus().stream().map(item -> item.getPromotionSessionId() + "_" + item.getSkuId()).collect(Collectors.toList());
                stringRedisTemplate.opsForList().leftPushAll(SeckillConstant.SESSIONS_CACHE_PREFIX + key, ids);
            }
            stringRedisTemplate.expire(SeckillConstant.SESSIONS_CACHE_PREFIX + key, 4, TimeUnit.DAYS);
        });
    }

    private void saveSessionSkuInfos(List<SeckillSessionsWithSkus> data) {
        data.forEach(session -> {
            BoundHashOperations<String, Object, Object> ops = stringRedisTemplate.boundHashOps(SeckillConstant.SKUKILL_CACHE_PREFIX);
            session.getRelationSkus().forEach(seckillSkuVo -> {
                if (!ops.hasKey(seckillSkuVo.getPromotionSessionId() + "_" + seckillSkuVo.getSkuId())) {
                    String randomCode = UUID.randomUUID().toString().replace("-", "");
                    SeckillSkuRedisTo seckillSkuRedisTo = new SeckillSkuRedisTo();
                    BeanUtils.copyProperties(seckillSkuVo, seckillSkuRedisTo);
                    R r = productFeignService.info(seckillSkuVo.getSkuId());
                    if (r.getCode() == 0) {
                        seckillSkuRedisTo.setSkuInfo(r.getData("skuInfo", new TypeReference<SkuInfoVo>() {
                        }));
                    }
                    seckillSkuRedisTo.setStartTime(session.getStartTime().getTime());
                    seckillSkuRedisTo.setEndTime(session.getEndTime().getTime());
                    seckillSkuRedisTo.setRandomCode(randomCode);
                    ops.put(seckillSkuVo.getPromotionSessionId() + "_" + seckillSkuVo.getSkuId(), JSON.toJSONString(seckillSkuRedisTo));
                    ops.expire(4, TimeUnit.DAYS);
                    RSemaphore semaphore = redissonClient.getSemaphore(SeckillConstant.SKU_STOCK_SEMAPHORE + randomCode);
                    semaphore.trySetPermits(seckillSkuVo.getSeckillCount().intValue());
                }
            });
        });
    }

}
